import hashlib
import logging
from utils import wx_method

from django.conf import settings
from utils.decorators import json_check, check_login
from utils.common_utils import json_response

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


#@check_login
def get_sign(request):
    '''
    生成签名算法;
    返回微信config接口注入权限验证配置参数;
    '''
    url = request.GET.get('url', '')
    ok, access_token = wx_method.get_token()
    if not ok:
        return json_response({"code": 1000, "message": "获取access_token失败"})
    ok, jsapi_ticket = wx_method.get_jsapi_ticket(access_token)
    if not ok:
        return json_response({"code": 1000, "message": "获取jsapi_ticket失败"})
    # 获取随机字符串和时间戳
    noncestr = wx_method.create_noncestr()
    timestamp = wx_method.create_timestamp()
    # 组合签名字符串
    origin_string = "jsapi_ticket={}&noncestr={}&timestamp={}&url={}".format(jsapi_ticket, noncestr, timestamp, url)
    crypt = hashlib.sha1(origin_string.encode('utf-8'))
    signature = crypt.hexdigest()
    error_logger.info('signature:{}'.format(signature))
    result_dict = {
        "nonceStr": noncestr,
        "timestamp": timestamp,
        "signature": signature,
        "appId": settings.WX_APP_ID,
    }
    error_logger.info('result_dict:{}'.format(result_dict))
    return json_response({"code": 0, "message": "", "data": result_dict})


def get_share_qrcode(request):
    topic_id = request.GET.get('topic_id', '')
    scene = request.GET.get('scene', '')
    page = request.GET.get('page', '')
    category = request.GET.get('category', '0')
    if topic_id and scene:
        file_name = '%s_%s' % (category, topic_id)
        code, result = wx_method.create_qrcode(file_name=file_name, scene=scene, page=page)
        return json_response({"code": code, "message": result})        
    else:
        return json_response({"code": 1000, "message": "参数错误"})
